RulesTable = function (states) {
    this._initialState = states[0];
    this._states = {};
    this._statesInOrder = new Array();
    for (var idx in states) {
        var state = states[idx];
        this._states[state.getName()] = state;
        this._statesInOrder.push(state);
    }
};

RulesTable.prototype = {
    getState:function (stateName) {
        return this._states[stateName];
    },

    getInitialState:function () {
        return this._initialState;
    },

    getStates:function () {
        return this._states;
    },

    getStatesInOrder: function() {
        return this._statesInOrder;
    },

    addState:function (stateName, alphabet, rules) {
        var state = new State(stateName);
        var symbols = alphabet.getSymbols();
        if (rules) {
            for (var i in rules) {
                state.addRule(rules[i][0], rules[i][1]);
            }
        } else {
            for (var i in symbols) {
                var symbol = symbols[i];
                state.addRule(symbol, new Rule(Rule.MoveType.RIGHT, symbol, stateName));
            }
        }
        this._states[stateName] = state;
        var found = false;
        for(var i in this._statesInOrder) {
            if (this._statesInOrder[i].getName() === stateName) {
                this._statesInOrder[i] = state;
                found = true;
                break;
            }
        }
        if (!found)
            this._statesInOrder.push(state);
    },

    removeState:function (stateName, alphabet) {
        var symbols = alphabet.getSymbols();
        for (var i in this._states) {
            var state = this._states[i];
            for (var j in symbols) {
                var symbol = symbols[j];
                var rule = state.getRule(symbol);
                if (typeof (rule) !== 'undefined') {
                    var newTargetState = rule.getTargetStateName() === stateName ? 'HALT' : rule.getTargetStateName();
                    state.addRule(symbol, new Rule(rule.getMoveType(), rule.getSymbolToWrite(), newTargetState));
                }
            }
        }
        var newInOrder = new Array();
        for(var i in this._statesInOrder)
            if (this._statesInOrder[i].getName() !== stateName)
                newInOrder.push(this._statesInOrder[i]);
        this._statesInOrder = newInOrder;
        delete this._states[stateName];
    }
};
